package com.qg.utils;

import com.qg.config.KafkaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Kafka 工具类
 */
@Component
public class KafkaUtil {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private KafkaConfig kafkaConfig;

    /**
     * 发送普通日志的方法
     * @param message
     * @return
     */
    public String sendInfoMessage(String message){
        /**
         * 输入 项目名 日志级别 具体消息
         * user 普通日志->user-info   user 错误日志->user-error
         * user user-info user-error
         */
        try {
            kafkaTemplate.send(kafkaConfig.getModuleName()+"-"+KafkaConfig.LogType.INFO,KafkaConfig.qgKey,message);
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }

        return "success";
    }
    /**
     * 发送异常日志的方法
     * @param em
     * @return
     */
    public String sendErrorMessage(Exception em){
        /**
         * 输入 项目名 日志级别 具体消息
         * user 普通日志->user-info   user 错误日志->user-error
         * user user-info user-error
         */
        try {
            Writer writer=new StringWriter();
            PrintWriter pw=new PrintWriter(writer);
            em.printStackTrace(pw);
            kafkaTemplate.send(kafkaConfig.getModuleName()+"-"+KafkaConfig.LogType.ERROR,KafkaConfig.qgKey,writer.toString());
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }

        return "success";
    }
}
